import { message } from 'antd'
import { MutableRefObject, useEffect, useRef } from 'react'

export function useCameraMedia(props: {
  videoRef: MutableRefObject<HTMLVideoElement | null>
  canvasRef: MutableRefObject<HTMLCanvasElement | null>
  onLoad?: () => void
}) {
  const { videoRef, canvasRef, onLoad } = props
  const streamRef = useRef<MediaStream>()

  const openVideo = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: true,
        audio: false,
      })
      streamRef.current = stream
      if (videoRef.current) {
        videoRef.current.srcObject = stream
      }
      onLoad?.()
    } catch {
      message.error('获取视频流失败，请检查摄像头访问权限')
    }
  }

  const closeVideo = () => {
    if (videoRef.current && videoRef.current.srcObject) {
      const tracks = streamRef.current?.getTracks()
      tracks?.forEach((track) => {
        if (track.readyState === 'live') {
          track.stop()
        }
      })
      videoRef.current.pause()
      videoRef.current.srcObject = null
    }
  }

  useEffect(() => {
    openVideo()
    return () => closeVideo()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const takePhoto = () => {
    if (!videoRef.current || !canvasRef.current) {
      message.error('照片拍摄失败，请重试')
      return
    }
    const video = videoRef.current
    const canvas = canvasRef.current
    const context = canvas.getContext('2d')
    if (!context) {
      message.error('照片拍摄失败，请重试')
      return
    }
    canvas.width = video.videoWidth
    canvas.height = video.videoHeight
    context.drawImage(video, 0, 0, canvas.width, canvas.height)
    const imageData = canvas.toDataURL('image/png')
    return imageData
  }

  return { takePhoto, closeVideo }
}
